<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multi-Tab Sync Chat</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 500px;
            height: 600px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, #ff6b6b, #ffa726);
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }

        .header h1 {
            font-size: 1.8em;
            margin-bottom: 8px;
        }

        .header p {
            opacity: 0.9;
            font-size: 0.9em;
        }

        .status {
            position: absolute;
            top: 15px;
            right: 20px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 0.8em;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #4caf50;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .demo-info {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
            padding: 15px;
            margin: 20px;
            border-radius: 8px;
            font-size: 0.9em;
            line-height: 1.4;
        }

        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            scroll-behavior: smooth;
        }

        .message {
            background: #f5f5f5;
            padding: 12px 16px;
            border-radius: 18px;
            margin-bottom: 12px;
            max-width: 80%;
            word-wrap: break-word;
            animation: slideIn 0.3s ease-out;
            position: relative;
        }

        .message.own {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            margin-left: auto;
            text-align: right;
        }

        .message.sync {
            background: linear-gradient(45deg, #ff6b6b, #ffa726);
            color: white;
            border: 2px solid #fff;
            box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
        }

        .sync-indicator {
            font-size: 0.7em;
            opacity: 0.8;
            margin-top: 4px;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .input-container {
            padding: 20px;
            background: rgba(255, 255, 255, 0.9);
            border-top: 1px solid #eee;
        }

        .input-wrapper {
            display: flex;
            gap: 12px;
            align-items: center;
        }

        #messageInput {
            flex: 1;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: all 0.3s ease;
        }

        #messageInput:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        #sendButton {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            width: 48px;
            height: 48px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 20px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #sendButton:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
        }

        #sendButton:active {
            transform: scale(0.95);
        }

        .empty-state {
            text-align: center;
            color: #999;
            font-style: italic;
            margin-top: 50px;
        }

        .tab-indicator {
            position: absolute;
            top: 15px;
            left: 20px;
            background: rgba(255, 255, 255, 0.2);
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8em;
            font-weight: bold;
        }

        @media (max-width: 600px) {
            .container {
                height: 100vh;
                border-radius: 0;
                max-width: none;
            }
            
            .demo-info {
                margin: 10px;
                padding: 10px;
                font-size: 0.8em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="tab-indicator" id="tabId">Tab #1</div>
            <div class="status">
                <div class="status-dot"></div>
                <span>Live Sync</span>
            </div>
            <h1>Multi-Tab Chat</h1>
            <p>Messages sync instantly across all open tabs</p>
        </div>

        <div class="demo-info">
            <strong>🚀 Demo Instructions:</strong> Open this page in multiple browser tabs, then type a message in any tab. Watch it appear instantly in all other tabs! No backend required - uses Broadcast Channel API.
        </div>

        <div class="chat-container">
            <div class="messages" id="messages">
                <div class="empty-state">
                    Start typing to see the magic happen! ✨
                </div>
            </div>

            <div class="input-container">
                <div class="input-wrapper">
                    <input 
                        type="text" 
                        id="messageInput" 
                        placeholder="Type your message..."
                        maxlength="500"
                    >
                    <button id="sendButton" title="Send message">
                        ➤
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        class MultiTabChat {
            constructor() {
                this.messages = [];
                this.tabId = this.generateTabId();
                this.channel = new BroadcastChannel('chat-sync');
                this.init();
            }

            generateTabId() {
                return Math.random().toString(36).substr(2, 9);
            }

            init() {
                // Update tab indicator
                document.getElementById('tabId').textContent = `Tab #${this.tabId.substr(0, 3)}`;

                // Set up event listeners
                this.setupEventListeners();

                // Load existing messages from memory (if any)
                this.loadMessages();

                // Listen for messages from other tabs
                this.channel.addEventListener('message', (event) => {
                    this.handleIncomingMessage(event.data);
                });

                // Send welcome message
                setTimeout(() => {
                    this.addWelcomeMessage();
                }, 500);
            }

            setupEventListeners() {
                const input = document.getElementById('messageInput');
                const button = document.getElementById('sendButton');

                button.addEventListener('click', () => this.sendMessage());
                
                input.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        this.sendMessage();
                    }
                });

                // Auto-focus input
                input.focus();
            }

            sendMessage() {
                const input = document.getElementById('messageInput');
                const text = input.value.trim();

                if (!text) return;

                const message = {
                    id: Date.now() + '-' + this.tabId,
                    text: text,
                    timestamp: new Date(),
                    sender: this.tabId,
                    isOwn: true
                };

                // Add to local messages
                this.messages.push(message);
                this.renderMessage(message);

                // Broadcast to other tabs
                this.channel.postMessage({
                    type: 'new-message',
                    message: {
                        ...message,
                        isOwn: false // Mark as external for other tabs
                    }
                });

                // Clear input
                input.value = '';
                input.focus();

                // Scroll to bottom
                this.scrollToBottom();
            }

            handleIncomingMessage(data) {
                if (data.type === 'new-message') {
                    const message = {
                        ...data.message,
                        isSync: true // Mark as synced message
                    };
                    
                    // Avoid duplicates
                    if (!this.messages.find(m => m.id === message.id)) {
                        this.messages.push(message);
                        this.renderMessage(message);
                        this.scrollToBottom();
                    }
                }
            }

            renderMessage(message) {
                const messagesContainer = document.getElementById('messages');
                
                // Remove empty state
                const emptyState = messagesContainer.querySelector('.empty-state');
                if (emptyState) {
                    emptyState.remove();
                }

                const messageEl = document.createElement('div');
                messageEl.className = 'message';
                
                if (message.isOwn) {
                    messageEl.classList.add('own');
                } else if (message.isSync) {
                    messageEl.classList.add('sync');
                }

                const timeStr = new Date(message.timestamp).toLocaleTimeString([], {
                    hour: '2-digit',
                    minute: '2-digit'
                });

                messageEl.innerHTML = `
                    <div>${this.escapeHtml(message.text)}</div>
                    ${message.isSync ? `<div class="sync-indicator">↻ Synced from Tab #${message.sender.substr(0, 3)}</div>` : ''}
                `;

                messagesContainer.appendChild(messageEl);
            }

            addWelcomeMessage() {
                const welcomeMessage = {
                    id: 'welcome-' + this.tabId,
                    text: `🎉 Welcome! This is Tab #${this.tabId.substr(0, 3)}. Open more tabs to see real-time sync in action!`,
                    timestamp: new Date(),
                    sender: 'system',
                    isOwn: true
                };

                this.messages.push(welcomeMessage);
                this.renderMessage(welcomeMessage);
                this.scrollToBottom();
            }

            loadMessages() {
                // In a real app, you might load from localStorage or indexedDB
                // For this demo, we start fresh each time
            }

            scrollToBottom() {
                const messagesContainer = document.getElementById('messages');
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }

            escapeHtml(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }
        }

        // Check if Broadcast Channel is supported
        if ('BroadcastChannel' in window) {
            // Initialize the chat app
            const chat = new MultiTabChat();
        } else {
            // Fallback message for unsupported browsers
            document.body.innerHTML = `
                <div style="text-align: center; padding: 50px; font-family: Arial, sans-serif;">
                    <h2>Browser Not Supported</h2>
                    <p>This demo requires a browser that supports the Broadcast Channel API.</p>
                    <p>Please try Chrome, Firefox, or Safari.</p>
                </div>
            `;
        }
    </script>
</body>
</html>
